package com.jumi.microservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jumi.microservice.common.base.dto.BasePageResponse;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.common.constant.RequestConstant;
import com.jumi.microservice.common.utils.ResultGenerator;
import com.jumi.microservice.constant.ExceptionEnum;
import com.jumi.microservice.constant.PriorTypeEnum;
import com.jumi.microservice.domain.Account;
import com.jumi.microservice.domain.Priority;
import com.jumi.microservice.domain.dto.AccountDTO;
import com.jumi.microservice.domain.dto.PriorityDTO;
import com.jumi.microservice.domain.vo.PriorityVO;
import com.jumi.microservice.service.AccountService;
import com.jumi.microservice.service.PriorityService;
import com.jumi.microservice.utils.HttpRquestUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 权限表 前端控制器
 * </p>
 *
 * @author liuz
 * @since 2020-07-18
 */
@RestController
@Api(tags = "权限表 相关接口")
@RequestMapping("/auth/priority")
public class PriorityController {

    @Autowired
    private PriorityService priorityService;

    @Autowired
    private AccountService accountService;


    @ApiOperation(value = "新增数据", notes = "新增一条权限表数据")
    @PostMapping("/add")
    public ResponseResult add(@Validated @RequestBody PriorityVO priority, HttpServletRequest request) {
        //vo->dto
        PriorityDTO dto = vo2Dto(priority);
        Account ac = accountById(HttpRquestUtil.getUserId(request));
        if(ac!=null){
            dto.setCreater(ac.getUserName());
            dto.setModifier(ac.getUserName());
        }
        priorityService.insert(dto);
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "删除数据", notes = "删除指定ID权限表数据")
    @ApiImplicitParam(name = "id", value = "ID")
    @DeleteMapping("/delete")
    public ResponseResult delete(@RequestParam Long id, HttpServletRequest request) {
        String username = null;
        Account ac = accountById(HttpRquestUtil.getUserId(request));
        if(ac!=null){
            username = ac.getUserName();
        }
        priorityService.delete(id, username);
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "更新数据", notes = "更新指定ID权限表数据")
    @PutMapping("/update")
    public ResponseResult update(@Validated @RequestBody PriorityVO priority, HttpServletRequest request) {
        PriorityDTO dto = vo2Dto(priority);
        Account ac = accountById(HttpRquestUtil.getUserId(request));
        if(ac!=null){
            dto.setCreater(ac.getUserName());
            dto.setModifier(ac.getUserName());
        }
        priorityService.update(dto);
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "查询数据", notes = "获取指定ID权限表数据")
    @ApiImplicitParam(name = "id", value = "ID")
    @GetMapping("/detail")
    public ResponseResult<PriorityVO> detail(@RequestParam Long id) {
        PriorityDTO priority = priorityService.selectById(id);
        return ResultGenerator.genSuccessResult(dto2Vo(priority));
    }


    @ApiOperation(value = "启用/停用", notes = "菜单的启用/停用")
    @PostMapping("/enabled")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键id"),
            @ApiImplicitParam(name = "status", value = "启用状态"),
    })
    public ResponseResult enabled(@RequestParam Long id, @RequestParam Integer status) {
        priorityService.enabledStatus(id,status);
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "查询分页", notes = "获取权限表分页列表数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码"),
            @ApiImplicitParam(name = "size", value = "分页大小"),
    })
    @GetMapping("/list")
    public BasePageResponse list(
            @RequestParam(defaultValue = "0") Integer page,
            @RequestParam(defaultValue = "0") Integer size,
            PriorityVO priority) {
        LambdaQueryWrapper<Priority> wrapper = Wrappers.lambdaQuery();
        wrapper.like(StringUtils.isNotEmpty(priority.getPriorityName()),Priority::getPriorityName,priority.getPriorityName());
        wrapper.eq(priority.getStatus()!=null,Priority::getStatus,priority.getStatus());
        wrapper.ge(StringUtils.isNotEmpty(priority.getStartTimeAdd()),Priority::getCreateTime,priority.getStartTimeAdd());
        wrapper.le(StringUtils.isNotEmpty(priority.getEndTimeAdd()),Priority::getCreateTime,priority.getEndTimeAdd());
        wrapper.ge(StringUtils.isNotEmpty(priority.getStartTimeUp()),Priority::getUpdateTime,priority.getStartTimeUp());
        wrapper.le(StringUtils.isNotEmpty(priority.getEndTimeUp()),Priority::getUpdateTime,priority.getEndTimeUp());
        wrapper.eq(Priority::getIsDel,0);
        wrapper.orderByDesc(Priority::getOrderNum,Priority::getUpdateTime);
        IPage<Priority> pageInfo = priorityService.page(
                new Page<>(page, size),wrapper);
        return ResultGenerator.genSuccessResultPage(pos2Vos(pageInfo.getRecords()),pageInfo.getTotal());
    }

    @ApiOperation(value = "查询模块", notes = "获取模块分页数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码"),
            @ApiImplicitParam(name = "size", value = "分页大小"),
    })
    @GetMapping("/root")
    public ResponseResult<IPage<Priority>> root(
            @RequestParam(defaultValue = "0") Integer page,
            @RequestParam(defaultValue = "0") Integer size) {
        LambdaQueryWrapper<Priority> wrapper = Wrappers.lambdaQuery();
        //根目录不返回
        wrapper.ne(Priority::getParentId,0);
        wrapper.eq(Priority::getPriorityType, PriorTypeEnum.MODULE.getCode());
        wrapper.eq(Priority::getIsDel,0);
        wrapper.orderByDesc(Priority::getOrderNum,Priority::getUpdateTime);
        IPage<Priority> pageInfo = priorityService.page(
                new Page<>(page, size),wrapper);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @ApiOperation(value = "查询子权限列表", notes = "查询子权限列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码"),
            @ApiImplicitParam(name = "size", value = "分页大小"),
            @ApiImplicitParam(name = "id", value = "ID")
    })
    @GetMapping("/child")
    public ResponseResult<IPage<Priority>> child(
            @RequestParam(defaultValue = "0") Integer page,
            @RequestParam(defaultValue = "0") Integer size,
            @RequestParam Integer id) {
        LambdaQueryWrapper<Priority> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Priority::getParentId,id);
        wrapper.eq(Priority::getIsDel,0);
        wrapper.orderByDesc(Priority::getOrderNum,Priority::getUpdateTime);
        IPage<Priority> pageInfo = priorityService.page(
                new Page<>(page, size),wrapper);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @ApiOperation(value = "角色权限", notes = "新增/编辑角色获取权限")
    @ApiImplicitParam(name = "id", value = "ID")
    @GetMapping("/rolePriors")
    public ResponseResult<List<PriorityVO>> rolePriors(@RequestParam Long id) {
        List<PriorityVO> priority = priorityService.selectPriorsByRoleId(id);
        return ResultGenerator.genSuccessResult(priority);
    }

    @ApiOperation(value = "用户的权限", notes = "获取登录用户的权限")
    @ApiImplicitParam(name = "id", value = "ID")
    @GetMapping("/tree/authorized")
    public ResponseResult<List<PriorityVO>> authorizeList(@RequestParam Long id) {
        boolean isSuper = false;
        List<Priority> priority = priorityService.authorizeList(id,isSuper);
        return ResultGenerator.genSuccessResult(pos2Vos(priority));
    }

    /**
     * 对象转换 vo->dto
     * @param vo
     * @return
     */
    private PriorityDTO vo2Dto(PriorityVO vo){
        PriorityDTO r = null;
        try {
            r = vo.clone(PriorityDTO.class);
        }catch (Exception e){
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return r;
    }

    /**
     * 对象转换 dto->vo
     * @param dto
     * @return
     */
    private PriorityVO dto2Vo(PriorityDTO dto){
        PriorityVO r = null;
        try {
            r = dto.clone(PriorityVO.class);
        }catch (Exception e){
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return r;
    }

    private List<PriorityVO> pos2Vos(List<Priority> pos){
        List<PriorityVO> vos = pos.stream().map(p->{
            PriorityVO vo = null;{
                try {
                    vo = p.clone(PriorityVO.class);
                }catch (Exception e){
                    ExceptionEnum.FAIL_CHANGE.newException();
                }
            }
            return vo;
        }).collect(Collectors.toList());
        return vos;
    }

    /**
     * 获取登录用户
     * @param userId 主键id
     * @return
     */
    private Account accountById(Long userId) {
        AccountDTO ac = accountService.getAccountById(userId);
        try {
            return ac.clone(Account.class);
        }catch (Exception e){

        }
        return null;
    }
}
